import { onMounted } from 'vue';
import { useRouter } from 'vue-router';
import type { BaiduAnalyticOptions } from './baidu-analytic.js';
import { defineClientConfig } from '@vuepress/client';

declare global {
    interface Window { _hmt: any; }
}

// 初始化百度统计插件的配置参数
declare const __BAIDU_ANALYTICS_OPTIONS__: BaiduAnalyticOptions;
const options = __BAIDU_ANALYTICS_OPTIONS__;
const IGNORE_LOCAL = options.ignoreLocal;
const HM = options.hm;
const DOM_ID = 'baidu-analytic';


export const useBaiduAnalytic = (): void => {
    onMounted(() => {
        baiduSubmit(1000);

        // 监听路由
        const router = useRouter();
        router.afterEach((to, from) => {
            var toPath = to.path;
            var fromPath = from.path;
            // 忽略锚点
            if (toPath != fromPath) {
                baiduSubmit(500);
            }
        })
    })
}

function baiduSubmit(waitMS: number) {
    setTimeout(() => {
        baiduSubmitPush();
    }, waitMS);
}

function baiduSubmitPush() {
    if (HM && typeof window !== 'undefined') {
        // 忽略本地访问
        const host = window.location.host;
        if (IGNORE_LOCAL && (
            host.indexOf("127.0.0.1") != -1
            || host.indexOf("localhost") != -1
        )) {
            return;
        }

        // 删除已存在的统计 DOM Node
        var element = document.getElementById(DOM_ID);
        if (element) {
            element.remove();
        }

        // 触发统计
        window._hmt = window._hmt || [];
        const hm = document.createElement('script');
        hm.id = DOM_ID;
        hm.src = 'https://hm.baidu.com/hm.js?' + HM;
        const s = document.getElementsByTagName('script')[0];
        if (s.parentNode) {
            s.parentNode.insertBefore(hm, s);
            window._hmt.push(['_trackPageview', window.location.href]);
        }
    }
}

export default defineClientConfig({
    setup() {
        useBaiduAnalytic();
    }
})